package com.sdvdxl.beans;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.sdvdxl.exceptios.NetworkException;
import com.sdvdxl.exceptios.UnGrantException;
import com.sdvdxl.oauth.GrantManager;

/**
 * 用户基本信息<br>
 * @see SuperUser
 * @author sdvdxl (sdvdxl@163.com)
 *
 */
public class User {
	private String uid;// 用户id
	private String uname;// 用户名
	private String portrait;// 头像图片url
	protected String xmlURL;
	
	public User() throws UnGrantException, NetworkException {
		if (GrantManager.ACCESS_TOKEN==null) {
			throw new UnGrantException("没有权限，未取得access_token");
		}
		
		xmlURL = "https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?" 
				+ "access_token=" + GrantManager.ACCESS_TOKEN
				+ "&format=xml";
		getUserInf();
	}
	
	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public String getPortrait() {
		return portrait;
	}

	public void setPortrait(String portrait) {
		this.portrait = portrait;
	}
	
	private void getUserInf() throws NetworkException, UnGrantException {
		String basic = "//passport_users_getLoggedInUser_response/";
		Document doc = null;
		Node node = null;
		
		try {
			URL url = new URL(xmlURL);
			URLConnection uc = url.openConnection();

			doc = new SAXReader().read(uc.getInputStream());
		} catch (DocumentException | IOException e) {
			throw new NetworkException("网络异常" + e);
		}
		
		node = doc.selectSingleNode(basic + "uid");
		if (node==null) {
			throw new UnGrantException("未授权");
		}
		setUid(node.getText().trim());
		
		node = doc.selectSingleNode(basic + "uname");
		setUname(node.getText().trim());
		
		node = doc.selectSingleNode(basic + "portrait");
		setPortrait("http://himg.bdimg.com/sys/portraitn/item/" 
				+ node.getText().trim() + ".jpg");
		
		
	}
	
	@Override
	public String toString() {
		return "uid:" + uid
				+ " uname:" + uname
				+ " portrait:" + portrait;
	}

}
